#include "StdAfx.h"
#include <iostream>
#include <fstream>
#include <sstream>

#include "InputLoader.h"
#include "Triangle.h"
#include "Line.h"
#include "Constants.h"

bool InputLoader::LoadPrimitives(const string& strFileName, vector<CPrimitivePtr>& vPrimitives, bool bInput2D)
{
	bool bUseTexture = CConstants::GetInstance().IsTrue("USE_TEXTURE");

	fstream inputFileStream(strFileName, ios_base::in);

	// read triangles
	int iNumTriangles = 0;
	inputFileStream >> iNumTriangles;
	for (int i = 0; i < iNumTriangles; ++i)
	{
		CPrimitivePtr spTriangle(new CTriangle);

		for (int j = 0; j < 3; ++j)
		{
			CVertex& v = spTriangle->GetVertex(j);

			inputFileStream >> v.worldPosition[0];
			inputFileStream >> v.worldPosition[1];
			if (bInput2D)
				v.worldPosition[2] = 0;
			else
				inputFileStream >> v.worldPosition[2];
			v.worldPosition[3] = 1;

			inputFileStream >> v.color[0];
			inputFileStream >> v.color[1];
			inputFileStream >> v.color[2];
			inputFileStream >> v.color[3];

			if (!bInput2D)
			{
				inputFileStream >> v.normal[0];
				inputFileStream >> v.normal[1];
				inputFileStream >> v.normal[2];
			}

			if (bUseTexture)
			{
				inputFileStream >> v.texCoord[0];
				inputFileStream >> v.texCoord[1];
			}
		}
		vPrimitives.push_back(spTriangle);
	}

	// read lines
	int iNumLines = 0;
	inputFileStream >> iNumLines;
	for (int i = 0; i < iNumLines; ++i)
	{
		CPrimitivePtr spLine(new CLine);

		for (int j = 0; j < 2; ++j)
		{
			CVertex& v = spLine->GetVertex(j);

			inputFileStream >> v.worldPosition[0];
			inputFileStream >> v.worldPosition[1];
			if (bInput2D)
				v.worldPosition[2] = 0;
			else
				inputFileStream >> v.worldPosition[2];

			v.worldPosition[3] = 1;

			inputFileStream >> v.color[0];
			inputFileStream >> v.color[1];
			inputFileStream >> v.color[2];
			inputFileStream >> v.color[3];

			if (!bInput2D)
			{
				inputFileStream >> v.normal[0];
				inputFileStream >> v.normal[1];
				inputFileStream >> v.normal[2];
			}

			if (bUseTexture)
			{
				inputFileStream >> v.texCoord[0];
				inputFileStream >> v.texCoord[1];
			}
		}
		vPrimitives.push_back(spLine);
	}

	inputFileStream.close();

	return true;
}
